<?php
namespace App\Http\Controllers\Api\User\Auth;

use App\Http\Controllers\Api\Controller;
use Illuminate\Http\Request;
use App\Services\Base\UserService;
use App\Services\Base\Auth\UserService as AuthUserService;
use App\Services\Base\Auth\PolicyService as AuthPolicyService;
use App\Rules\Mobile;

class IndexController extends Controller
{

    /**
     * 用户登陆
     *
     * @param Request $request            
     * @return array
     */
    public function signIn(Request $request)
    {
        $this->validate($request, [
            'mobile' => [
                'required',
                new Mobile()
            ],
            'password' => 'required|between:6,16'
        ]);
        $mobile = $request->post('mobile');
        $password = $request->post('password');
        
        $userService = new UserService();
        // 查询用户数据（常规情况，根据项目情况调整）
        // $user = $userService->findUserByMobile($mobile);
        // 获取用户token（核心服务）
        $user = $userService->getUserToken($mobile, $password);
        
        $authUserService = new AuthUserService();
        // 验证用户密码、状态（常规情况，根据项目情况调整）
        // $authUserService->verifyUserPassword($user, $password)->verifyUserStatus($user);
        
        $authPolicyService = new AuthPolicyService();
        // 获取策略、验证权限（常规情况，根据项目情况调整）
        // $authPolicyService->selectPolicy($user)->verifyAuth();
        // 同步策略数据到 auth（常规情况，根据项目情况调整）
        // $authPolicyService->synAuthData($this->auth());
        
        // 同步用户数据到 auth
        // 使用缓存系统持久化，实际情况可以使用mysql
        $authUserService->synAuthData($this->identity(), $user);
        
        $data['token'] = $user['token'];
        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 用户退出
     *
     * @param Request $request            
     * @return array
     */
    public function signOut(Request $request)
    {
        // 授权数据（常规情况，根据项目情况调整）
        // $authPolicyService = new AuthPolicyService();
        // 同步数据到 auth（常规情况，根据项目情况调整）
        // $authPolicyService->synAuthData($this->auth());
        
        // 用户数据
        $authUserService = new AuthUserService();
        // 同步数据到 auth
        $authUserService->destroyAuthData($this->identity());
        
        return $this->response->setResponseData('退出成功')->getResponse();
    }
}